<script setup lang="ts">

import {useDictStore} from '@/stores'
import {
  DataTableBaseColumn,
  type DataTableColumns,
  DataTableFilterState,
  DataTableInst,
  FormInst,
  FormRules,
  NButton,
  NButtonGroup,
  NPopconfirm,
  NSpace,
  PaginationInfo,
  PaginationProps
} from "naive-ui";
import type {SysBizException} from "@/api/biz-exception/types.ts";
import {renderPermission, resetToNull} from "@/utils";
import {bizExceptionApi} from "@/api/biz-exception";

enum ModeTypeEnum {
  ADD = '新增',
  MODIFY = '修改'
}

interface PageQuery {
  bizCode: string
  bizExceptionStatus: number
}

const dictStore = useDictStore();
const pageQuery = reactive<PageQuery>(<PageQuery>{})
const tableLoading = ref(false);
const tableRef = ref<DataTableInst | null>(null)
const tableColumns = ref<DataTableColumns<SysBizException>>([
  {title: "业务异常编码", key: "bizCode", ellipsis: {tooltip: true}, resizable: true},
  {title: "业务异常信息", key: "bizMessage", ellipsis: {tooltip: true}, resizable: true},
  {
    title: "业务异常状态",
    key: "bizExceptionStatus",
    resizable: true,
    render: row => dictStore.renderTag('common-status', row.bizExceptionStatus),
    filter: true,
    filterMultiple: false,
    filterOptions: dictStore.getDictTextOptions('common-status')
  },
  {title: "创建时间", key: "createTime", ellipsis: {tooltip: true}, resizable: true},
  {title: '操作', key: 'action', align: 'center', render: row => tableActionRender(row)}
])
const tableData = ref<SysBizException[]>([])
const tablePagination = reactive<PaginationProps>({
  prefix: (info: PaginationInfo) => {
    return `共 ${info.itemCount} 条记录`
  },
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  itemCount: 0,
  pageCount: 0,
  onChange: (page: number) => {
    tablePagination.page = page
    handlePageQuery()
  },
  onUpdatePageSize: (pageSize: number) => {
    tablePagination.pageSize = pageSize
    tablePagination.page = 1
    handlePageQuery()
  }
})
const drawerDetailShow = ref(false)
const drawerDetailTitle = ref()
const drawerDetailFormRef = ref<FormInst | null>(null)
const drawerDetailSubmitLoading = ref(false)
const drawerDetailFormRules = reactive<FormRules>({
  bizCode: {trigger: ['blur'], required: true, message: '业务编码不能为空'},
  bizExceptionStatus: {trigger: ['blur'], required: true, message: '业务异常状态不能为空', type: 'number'},
  bizMessage: {trigger: ['blur'], required: true, message: '业务异常信息不能为空'}
})
const drawerDetailFormModel = reactive<SysBizException>({})

onMounted(() => {
  dictStore.loadDict(['common-status', 'server-name'])
  handlePageQuery()
})

const tableActionRender = (row: SysBizException) => {
  return h(NButtonGroup, {size: 'small'}, {
    default: () => [
      renderPermission(h(NButton, {
        tertiary: true,
        type: 'primary',
        onClick: () => handleClickModify(row)
      }, {default: () => '修改'}), 'biz-exception:modify'),
      h(NPopconfirm, {onPositiveClick: () => handleClickDelete(row.id)}, {
        trigger: () => renderPermission(h(NButton, {
          tertiary: true,
          type: 'error',
        }, {default: () => '删除'}), 'biz-exception:delete'),
        default: () => `确定删除该(${row.bizCode})业务异常吗？`
      })
    ]
  })
}
const handlePageQuery = () => {
  tableLoading.value = true
  bizExceptionApi.page({
    ...pageQuery,
    current: tablePagination.page ?? 1,
    size: tablePagination.pageSize ?? 10
  }).then(res => {
    tableData.value = res.data.records
    tablePagination.itemCount = res.data.total
    tablePagination.pageCount = res.data.pages
  }).finally(() => tableLoading.value = false)
}
const initDrawerDetail = (type: ModeTypeEnum) => {
  drawerDetailShow.value = true
  drawerDetailTitle.value = type
}
const handleClickReset = () => {
  resetToNull(pageQuery)
  tableRef.value?.filter(null)
  handlePageQuery()
}
const handleClickAdd = () => {
  initDrawerDetail(ModeTypeEnum.ADD)
  drawerDetailFormModel.bizExceptionStatus = dictStore.getDictDefault('common-status').dictValue as number
}
const handleClickModify = (row: SysBizException) => {
  if (row.id != null) {
    bizExceptionApi.detail(row.id).then(res => {
      Object.assign(drawerDetailFormModel, res.data)
      initDrawerDetail(ModeTypeEnum.MODIFY)
    })
  }
}
const handleClickDelete = (id: string) => {
  bizExceptionApi.delete(id).then(res => {
    window.$message?.success(res.message)
    handlePageQuery()
  })
}
const handleDrawerClose = () => {
  drawerDetailShow.value = false
  resetToNull(drawerDetailFormModel)
  handlePageQuery()
}
const handleClickSubmit = () => {
  drawerDetailSubmitLoading.value = true
  drawerDetailFormRef.value?.validate((errors) => {
    if (!errors) {
      switch (drawerDetailTitle.value) {
        case ModeTypeEnum.ADD:
          bizExceptionApi.add(drawerDetailFormModel).then(res => {
            window.$message?.success(res.message)
            drawerDetailShow.value = false
          })
          break;
        case ModeTypeEnum.MODIFY:
          bizExceptionApi.modify(drawerDetailFormModel).then(res => {
            window.$message?.success(res.message)
            drawerDetailShow.value = false
          })
      }
    }
  }).finally(() => drawerDetailSubmitLoading.value = false)
}
</script>
<template>
  <n-card class="biz-exception">
    <template #header>
      <n-space vertical>
        <n-space>
          <n-input v-model:value="pageQuery.bizCode" placeholder="业务编码" clearable/>
        </n-space>
        <n-space>
          <n-button
              secondary
              @click="handlePageQuery"
              :loading="tableLoading"
              v-p="'biz-exception:page'"
          >查询
          </n-button>
          <n-button
              secondary
              type="primary"
              @click="handleClickAdd"
              v-p="'biz-exception:add'"
          >新增
          </n-button>
          <n-button
              secondary
              type="warning"
              @click="handleClickReset">
            重置
          </n-button>
        </n-space>
      </n-space>
    </template>
    <n-data-table
        remote
        ref="tableRef"
        :loading="tableLoading"
        :columns="tableColumns"
        :data="tableData"
        :pagination="tablePagination"
        @update:filters="(filters: DataTableFilterState, {key}: DataTableBaseColumn) => {
          pageQuery[key] = filters[key]
          handlePageQuery()
        }"
    />
  </n-card>
  <n-drawer
      v-model:show="drawerDetailShow"
      :width="600"
      placement="right"
      :on-after-leave="handleDrawerClose"
      :auto-focus="false"
      :mask-closable="false"
      close-on-esc
  >
    <n-drawer-content :title="drawerDetailTitle" closable>
      <n-form
          ref="drawerDetailFormRef"
          :model="drawerDetailFormModel"
          :rules="drawerDetailFormRules"
      >
        <n-grid :cols="24" :x-gap="12">
          <n-form-item-gi v-if="drawerDetailTitle === ModeTypeEnum.MODIFY" :span="24" label="主键" path="id">
            <n-tag type="primary">{{ drawerDetailFormModel.id }}</n-tag>
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="业务编码" path="bizCode">
            <n-input v-model:value="drawerDetailFormModel.bizCode" placeholder="请输入业务编码" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="业务异常信息" path="bizMessage">
            <n-input type="textarea" v-model:value="drawerDetailFormModel.bizMessage" placeholder="请输入业务异常信息"
                     clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="业务异常状态" path="bizExceptionStatus">
            <n-select v-model:value="drawerDetailFormModel.bizExceptionStatus"
                      :options="dictStore.getDictTagOptions('common-status')" placeholder="请选择业务异常状态"
                      clearable/>
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <template #footer>
        <n-button secondary type="primary" @click="handleClickSubmit" :loading="drawerDetailSubmitLoading">提交
        </n-button>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>
<style scoped>
</style>
